package cn.pconline.autoclub.web.wap;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.StatusLine;
import org.apache.http.util.EntityUtils;
import org.gelivable.webmvc.JSONBuilder;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.pconline.autoclub.config.SystemConfig;
import cn.pconline.autoclub.entity.Club;
import cn.pconline.autoclub.entity.ClubAddress;
import cn.pconline.autoclub.entity.ClubAwardRecord;
import cn.pconline.autoclub.entity.ClubDraft;
import cn.pconline.autoclub.entity.ClubLevel;
import cn.pconline.autoclub.entity.ClubMember;
import cn.pconline.autoclub.entity.DynaInfo;
import cn.pconline.autoclub.entity.InviteJoin;
import cn.pconline.autoclub.entity.MemberApplication;
import cn.pconline.autoclub.entity.Promotion;
import cn.pconline.autoclub.entity.Theme;
import cn.pconline.autoclub.entity.UpgradeRule;
import cn.pconline.autoclub.entity.User;
import cn.pconline.autoclub.service.ActivityService;
import cn.pconline.autoclub.service.AlbumService;
import cn.pconline.autoclub.service.ClubAwardRecordService;
import cn.pconline.autoclub.service.ClubDraftService;
import cn.pconline.autoclub.service.ClubLevelService;
import cn.pconline.autoclub.service.ClubService;
import cn.pconline.autoclub.service.ClubUpgradePrizeService;
import cn.pconline.autoclub.service.CommentService;
import cn.pconline.autoclub.service.DynaService;
import cn.pconline.autoclub.service.IntfService;
import cn.pconline.autoclub.service.InviteJoinService;
import cn.pconline.autoclub.service.MemberService;
import cn.pconline.autoclub.service.MessageService;
import cn.pconline.autoclub.service.PromotionService;
import cn.pconline.autoclub.service.StatService;
import cn.pconline.autoclub.service.ThemeService;
import cn.pconline.autoclub.service.TopicService;
import cn.pconline.autoclub.service.UpgradeRuleService;
import cn.pconline.autoclub.service.UserForumService;
import cn.pconline.autoclub.service.UserService;
import cn.pconline.autoclub.util.AppUtils;
import cn.pconline.autoclub.util.DateUtils;
import cn.pconline.autoclub.util.EncodeUtils;
import cn.pconline.autoclub.util.JsonResult;
import cn.pconline.autoclub.util.Pager;
import cn.pconline.autoclub.util.Regex;
import cn.pconline.autoclub.util.RegionUtil;
import cn.pconline.autoclub.util.WebUtils;
import cn.pconline.autoclub.util.WhoisUtil;
import cn.pconline.autoclub.web.UserAuth;
import cn.pconline.passport2.Passport;
import cn.pconline.r.client.EntityBuilder;
import cn.pconline.r.client.ResponseExtractor;
import cn.pconline.r.client.SimpleHttpTemplate;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

@Controller
@RequestMapping("/wap/club")
public class ClubAction {

    @Autowired
    private UserAuth userAuth;
    @Autowired
    private UserService userService;
    @Autowired
    private SystemConfig systemConfig;
    @Autowired
    private ClubService clubService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private AlbumService albumService;
    @Autowired
    private TopicService topicService;
    @Autowired
    private DynaService dynaService;
    @Autowired
    private ActivityService activityService;
    @Autowired
    private UserForumService userForumService;
    @Autowired
    private IntfService intfService;
    @Autowired
    private PromotionService promotionService;
    @Autowired
    private ClubLevelService clubLevelService;
    @Autowired
    private ClubAwardRecordService recordService;
    @Autowired
    private ClubUpgradePrizeService prizeService;
    @Autowired
    private ThemeService themeService;
    @Autowired
    private ClubDraftService clubDraftService;
    @Autowired
    private SimpleHttpTemplate simpleHttpTemplate;
    @Autowired
    private InviteJoinService inviteJoinService;
	@Autowired
	private UpgradeRuleService upgradeRuleService;
    @Autowired
    private Passport passport;
    protected static final org.slf4j.Logger log = LoggerFactory.getLogger(ClubAction.class);
    private final static int PAGE_NUM = 1;
    private final static int PAGE_SIZE = 20;
    final static int MAX_PAGESIZE = 100;
    final static int MIN_PAGESIZE = 1;
    private static final String ERROR_PAGE_URL = "http://m.pcauto.com.cn/x/404/";
    private static final String ERROR_PAGE_REDIRECT_URL = "redirect:http://m.pcauto.com.cn/x/404/";
    //private static final String CLUB_INDEX_REDIRECT = "redirect:http://m.pcauto.com.cn/club/";
    private static final int STATUS_FALT = -1;
    private static final int STATUS_SUCCESS = 0;
    private static final int INPUT_MAX_LENGTH = 30;
    private final static int DEF_SOURCE_AGENT = 2;
    private final static String ACT_SAVE = "save";
    /**个人中心 性别  1-男**/
    private static final int MALE = 1;
    /**个人中心 性别  2-女**/
    private final static int FEMALE = 2;
    /**显示最新加入的成员数**/
    final static int DISPLAY_LASTEST_COUNT = 5;
    // 5: 人数油值满足
    static final int CAN_UP_LEVEL = 5;
    @RequestMapping("/myClub.do")
    public String myClub(HttpServletRequest request, HttpServletResponse resp) {
        User user = userAuth.getUser(request, resp); // 登录校验
        if (user.getUid() <= 0) {
            return "redirect:" + systemConfig.getUcRoot() + "/my/passport/login.jsp?return=" + systemConfig.getWapRoot() + "/myClub/";
        }
        request.setAttribute("user", user);
        return "/template/wap/club/my_club";
    }

    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(HttpServletRequest request, HttpServletResponse resp) {
        long clubId = WebUtils.paramLong(request, "clubId", 0);
        if (clubId < 1) {
            return ERROR_PAGE_REDIRECT_URL;
        }
        Club club = clubService.getValidClub(clubId);
        request.setAttribute("albumSum", albumService.countAlbumByClubId(club.getClubId()));
        request.setAttribute("photoSum", albumService.countPhotoByClubId(club.getClubId()));
        request.setAttribute("topicSum", dynaService.countDynaNumByType(club.getClubId(), DynaInfo.TYPE_TOPIC));
        request.setAttribute("activitySum", activityService.countActivityByClubId(club.getClubId()));
        request.setAttribute("club", club);
        User user = userAuth.getUser(request, resp);
        request.setAttribute("user", user);
        request.setAttribute("isMember", memberService.isClubMember(user.getUid(), club.getClubId()));
        if (user.getUid() > 0) {
            MemberApplication memberApplication = memberService.getMemberApplication(club.getClubId(), user.getUid(), MemberApplication.STATUS_UNAUDITED);
            request.setAttribute("isApply", memberApplication != null);
        } else {
            request.setAttribute("isApply", false);
        }

        return "/template/wap/club/index";
    }

    @RequestMapping("/apply")
    public String apply(HttpServletRequest request, HttpServletResponse response) {
        long clubId = WebUtils.paramLong(request, "clubId", 0);

        Club club = clubService.getValidClub(clubId);
        if (clubId == 0 || club == null) { // 404
            return ERROR_PAGE_REDIRECT_URL;
        }
        request.setAttribute("club", club);
        return "/template/wap/club/apply";
    }

    /**
     *
     * @param request
     * @param response
     * @return statusCode: 0: 跳转 1: 信息
     * @throws IOException
     */
    @RequestMapping(value = "/toApply", method = RequestMethod.GET)
    @ResponseBody
    public void toApply(HttpServletRequest request, HttpServletResponse response) throws IOException {
        WebUtils.setEncoding(request, response);
        JSONObject json = new JSONObject();
        String callback = WebUtils.param(request, "callback", "");

        User user = userAuth.getUser(request, response);
        long clubId = WebUtils.paramLong(request, "clubId", 0);
        Club club = clubService.getValidClub(clubId);
        if (clubId == 0 || club == null) { // 404
            json.put("statusCode", 0);
            json.put("url", ERROR_PAGE_URL);
            if (StringUtils.isBlank(callback)) {
                response.getWriter().println(json.toString());
            } else {
                response.getWriter().println(EncodeUtils.encodeForHTML(callback, 2) + "(" + json.toString() + ")");
            }
            response.getWriter().close();
            return;
        }

        if (user.getUid() <= 0) { // 未登录
            json.put("statusCode", 0);
            json.put("url", systemConfig.getUcRoot() + "/my/passport/login.jsp?return=" + systemConfig.getWapRoot() + "/" + request.getAttribute("myUrl") + "/");
            if (StringUtils.isBlank(callback)) {
                response.getWriter().println(json.toString());
            } else {
                response.getWriter().println(EncodeUtils.encodeForHTML(callback, 2) + "(" + json.toString() + ")");
            }
            response.getWriter().close();
            return;
        }

        // 判断有没有提交过申请
        List<MemberApplication> apps = memberService.findMemberApplication(user.getUid(), 0L, true);
        for (MemberApplication app : apps) {
            if (app.getClubId() == clubId) {
                json.put("message", "您已经申请加入了该车友会，请等候审核。");
                json.put("statusCode", 1);
                if (StringUtils.isBlank(callback)) {
                    response.getWriter().println(json.toString());
                } else {
                    response.getWriter().println(EncodeUtils.encodeForHTML(callback, 2) + "(" + json.toString() + ")");
                }
                response.getWriter().close();
                return;
            }
        }

        //判断是否已经加入了改车友会
        if (memberService.countByclubIdUid(clubId, user.getUid()) != null) {
            json.put("message", "您已经加入了该车友会。");
            json.put("statusCode", 1);
            if (StringUtils.isBlank(callback)) {
                response.getWriter().println(json.toString());
            } else {
                response.getWriter().println(EncodeUtils.encodeForHTML(callback, 2) + "(" + json.toString() + ")");
            }
            response.getWriter().close();
            return;
        }

        // 加入车友会数量超过限制
        int joinClubLimit = NumberUtils.toInt(systemConfig.getJoinClubLimit());
        int count = userService.updateJoinedClubCount(user);
        count += apps.size();
        count += clubService.findByFounder(user.getUid(), true).size();
        if (count >= joinClubLimit) {
            json.put("message", "您已经加入了其他车友会，无法申请。");
            json.put("statusCode", 1);
            if (StringUtils.isBlank(callback)) {
                response.getWriter().println(json.toString());
            } else {
                response.getWriter().println(EncodeUtils.encodeForHTML(callback, 2) + "(" + json.toString() + ")");
            }
            response.getWriter().close();
            return;
        }
        if (!user.isComplete() || StringUtils.isNotBlank(user.getCarInfo())) {
            json.put("url", systemConfig.getWapRoot() + "/" + request.getAttribute("myUrl") + "/apply/");

            // 本地测试 
            //json.put("url", systemConfig.getRoot() + "/wap/" + request.getAttribute("myUrl") + "/apply/");

            json.put("statusCode", 0);
            if (StringUtils.isBlank(callback)) {
                response.getWriter().println(json.toString());
            } else {
                response.getWriter().println(EncodeUtils.encodeForHTML(callback, 2) + "(" + json.toString() + ")");
            }
            response.getWriter().close();
            return;
        }

        String result = applyMembership(clubId, request, response);
        if (StringUtils.isEmpty(result)) {
            json.put("statusCode", 1);
            json.put("message", "申请完成！");
            if (StringUtils.isBlank(callback)) {
                response.getWriter().println(json.toString());
            } else {
                response.getWriter().println(EncodeUtils.encodeForHTML(callback, 2) + "(" + json.toString() + ")");
            }
            response.getWriter().close();
        } else {
            json.put("statusCode", 1);
            json.put("message", "申请失败，请联系管理员！");
            if (StringUtils.isBlank(callback)) {
                response.getWriter().println(json.toString());
            } else {
                response.getWriter().println(EncodeUtils.encodeForHTML(callback, 2) + "(" + json.toString() + ")");
            }
            response.getWriter().close();
        }
    }

    /**
     * 返回空串表示操作成功
     *
     * @param clubId
     * @param request
     * @param response
     * @return
     */
    private String applyMembership(long clubId, HttpServletRequest request, HttpServletResponse response) {
        User user = userAuth.getUser(request, response);
        if (user.getUid() <= 0) {
            return new JsonResult(JsonResult.STATUS_AUTH_FAILED, "没有登录").toString();
        }
        if (!user.isComplete() || StringUtils.isBlank(user.getCarInfo())) {
            int DB_MAX_LENGTH = 255;

            String phone = WebUtils.paramTrim(request, "phone", "");
            if (StringUtils.isNotEmpty(phone) && !phone.matches(Regex.cellphone.value)) {
                return new JsonResult(JsonResult.STATUS_ILLEGAL_STATE, "请输入正确的手机号码").toString();
            }
            user.setPhone(phone);
            String trueName = WebUtils.paramTrim(request, "truename", user.getUsername());
            if (StringUtils.isNotEmpty(trueName) && trueName.length() > DB_MAX_LENGTH) {
                return new JsonResult(JsonResult.STATUS_ILLEGAL_STATE, "请输入合法的姓名").toString();
            }
            user.setTruename(trueName);
            user.setGender(WebUtils.paramInt(request, "gender", 0));
            String provinceName = WebUtils.paramTrim(request, "provinceName", "");
            if (StringUtils.isNotEmpty(provinceName) && provinceName.length() > DB_MAX_LENGTH) {
                return new JsonResult(JsonResult.STATUS_ILLEGAL_STATE, "非法的省份名称").toString();
            }
            user.setProvince(provinceName);

            String cityName = WebUtils.paramTrim(request, "cityName", "");
            if (StringUtils.isNotEmpty(cityName) && cityName.length() > DB_MAX_LENGTH) {
                return new JsonResult(JsonResult.STATUS_ILLEGAL_STATE, "非法的城市名称").toString();
            }
            user.setCity(cityName);
            String brand = WebUtils.paramTrim(request, "brand", "");
            String serial = WebUtils.paramTrim(request, "serial", "");
            String brandName = WebUtils.paramTrim(request, "brandName", "");
            String serialName = WebUtils.paramTrim(request, "serialName", "");
            String carInfo = "";
            if (!brand.isEmpty() && !brand.equals("0") && !brandName.isEmpty()) {
                carInfo += brand + ";" + brandName + ";";
            }
            if (!serial.isEmpty() && !serial.equals("0") && !serialName.isEmpty()) {
                carInfo += serial + ";" + serialName + ";";
            }
            if (carInfo.endsWith(";")) {
                carInfo = carInfo.substring(0, carInfo.length() - 1);
            }
            if (carInfo.length() > DB_MAX_LENGTH) {
                return new JsonResult(JsonResult.STATUS_ILLEGAL_STATE, "非法的爱车信息").toString();
            }
            user.setCarInfo(carInfo);
            userService.updateUser(user);

        }
        if (!memberService.findMemberApplication(user.getUid(), clubId, true).isEmpty()) {
            return new JsonResult(JsonResult.STATUS_ILLEGAL_STATE, "您已经申请加入了该车友会，请等候审核。").toString();
        }
        if (memberService.countByclubIdUid(clubId, user.getUid()) != null) {
            return new JsonResult(JsonResult.STATUS_ILLEGAL_STATE, "您已经加入了该车友会。").toString();
        }
        int joinClubLimit = NumberUtils.toInt(systemConfig.getJoinClubLimit());
        int count = userService.updateJoinedClubCount(user);
        if (count >= joinClubLimit) {
            return new JsonResult(JsonResult.STATUS_ILLEGAL_STATE, "您已经加入了其他车友会，无法申请。").toString();
        }
        Club club = clubService.getValidClub(clubId);
        if (club == null) {
            return new JsonResult(JsonResult.STATUS_ILLEGAL_STATE, "车友会已经被锁定").toString();
        }
        memberService.applyMembership(user, club);//创建入会申请

        String clubUrl = clubService.getClubIndexUrl(club.getClubId(), club.getClubUrl());

        String msg1 = messageService.assembleClubUrl(club.getClubUrl(), club.getName());
        String msg2 = String.format("<a href=\"%s\" target=\"_blank\">%s</a>", clubUrl + "member/", "会员列表");

        //通知车友会管理员去审核
        List<ClubMember> admins = memberService.listAdmins(clubId);
        for (ClubMember m : admins) {
            messageService.send(userService.findUser(m.getUid()), MessageService.APPLY_RECEIVED, msg1, user.getNickname(), msg2);
        }
        return "";
    }

    @RequestMapping("/select")
    public String select(HttpServletRequest request, HttpServletResponse response) {

        return "/template/wap/club/select";
    }

    @RequestMapping("/doSelect")
    @ResponseBody
    public void doSelect(HttpServletRequest request, HttpServletResponse response) throws IOException {
        WebUtils.setEncoding(request, response);
        String callback = WebUtils.param(request, "callback", "");
        String provinceName = WebUtils.paramTrim(request, "provinceName", "");
        String cityName = WebUtils.paramTrim(request, "cityName", "");
        long brandId = WebUtils.paramLong(request, "brandId", 0);
        long serialId = WebUtils.paramInt(request, "serialId", 0);
        int pageNo = WebUtils.paramInt(request, "pageNo", 0);
        int pageSize = WebUtils.paramInt(request, "pageSize", 0, 0, MAX_PAGESIZE);
        JSONObject json = new JSONObject();
        json.put("list", clubService.select(provinceName, cityName, brandId, serialId, pageNo, pageSize));

        if (StringUtils.isBlank(callback)) {
            response.getWriter().println(json.toString());
        } else {
            response.getWriter().println(EncodeUtils.encodeForHTML(callback, 2) + "(" + json.toString() + ")");
        }
        response.getWriter().close();
    }

    @RequestMapping(value = "clubIndex", method = RequestMethod.GET)
    public String index1(HttpServletRequest request, HttpServletResponse response) {

        return "/template/wap/club/clubIndex";
    }

    /**
     * 车友会WAP版排行榜页面
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "listTopClub", method = RequestMethod.GET)
    public String listTop(HttpServletRequest request, HttpServletResponse response) {
        int type = WebUtils.paramInt(request, "type", ClubService.SORT_COUNTRY_TYPE);//1全国排名 2品牌排名 3省份排名
        User user = userAuth.getUser(request, response);
        ClubMember clubMember = memberService.findClubMemberByUserId(user.getUid());
        Club club = null;
        if (clubMember != null) {
            club = clubService.getClub(clubMember.getClubId());
        }
        List<Club> list20;
        List<Club> list5 = new ArrayList<Club>();
        String rankDesc = "";
        int rankVal = 0;
        //未登录，登录但没加入车友会，加入车友会但车友会是初建期
        if (type == ClubService.SORT_COUNTRY_TYPE || club == null || club.getLevelId() == 0) { // 全国排名
            // 获取前20名
            list20 = clubService.listClubBySortForList(
                    ClubService.SORT_COUNTRY_TYPE, PAGE_NUM, PAGE_SIZE, 0L,
                    0L, 0, 0);
            // 获取本车友会排名的前后2名
            if (club != null && club.getLevelId() > 0 && club.getRank() > 0) {
                int beginRank = club.getRank() - 2 <= 0 ? 1 : club.getRank() - 2;
                int endRank = club.getRank() + 2;
                list5 = clubService.listClubBySortForList(
                        ClubService.SORT_COUNTRY_TYPE, PAGE_NUM, PAGE_SIZE,
                        0L, 0L, beginRank, endRank);
                rankVal = club.getRank() - club.getDayRank();
                if (club.getDayRank() == 0) {//昨天没有排名的，当成没变化
                    rankVal = 0;
                }
            }
        } else if (type == ClubService.SORT_SERIES_TYPE && club.getLevelId() > 0) { // 品牌排名
            // 获取前20名
            list20 = clubService.listClubBySortForList(
                    ClubService.SORT_SERIES_TYPE, PAGE_NUM, PAGE_SIZE,
                    club.getBrandId(), 0L, 0, 0);
            // 获取本车友会排名的前后2名
            if (club.getBrandRank() > 0L) {
                int beginRank = club.getBrandRank() - 2 <= 0 ? 1 : club.getBrandRank() - 2;
                int endRank = club.getBrandRank() + 2;
                list5 = clubService.listClubBySortForList(
                        ClubService.SORT_SERIES_TYPE, PAGE_NUM, PAGE_SIZE,
                        club.getBrandId(), 0L, beginRank, endRank);
                rankVal = club.getBrandRank() - club.getDayBrandRank();
                if (club.getDayBrandRank() == 0) {//昨天没有排名的，当成没变化
                    rankVal = 0;
                }
            }
        } else if (type == ClubService.SORT_REGION_TYPE && club.getLevelId() > 0) { // 地区排名
            list20 = clubService.listClubBySortForList(
                    ClubService.SORT_REGION_TYPE, PAGE_NUM, PAGE_SIZE, 0L,
                    club.getProvinceId(), 0, 0);
            // 获取本车友会排名的前后2名
            if (club.getProvinceRank() > 0L) {
                int beginRank = club.getProvinceRank() - 2 <= 0 ? 1 : club.getProvinceRank() - 2;
                int endRank = club.getProvinceRank() + 2;
                list5 = clubService.listClubBySortForList(
                        ClubService.SORT_REGION_TYPE, PAGE_NUM, PAGE_SIZE,
                        0L, club.getProvinceId(), beginRank, endRank);
                rankVal = club.getProvinceRank() - club.getDayProvinceRank();
                if (club.getDayProvinceRank() == 0) {//昨天没有排名的，当成没变化
                    rankVal = 0;
                }
            }
        } else {
            return ERROR_PAGE_REDIRECT_URL;
        }
        List<Club> list = new ArrayList<Club>();
        if (list20 != null) {
            list.addAll(list20);
        }
        for (Club c : list5) {
            boolean isContain = false;
            for (Club t : list) {
                if (t.getClubId() == c.getClubId()) {
                    isContain = true;
                    break;
                }
            }
            if (!isContain) {
                list.add(c);
            }
        }
        if (rankVal > 0) {
            rankDesc = "下降";
        }
        if (rankVal < 0) {
            rankDesc = "上升";
        }
        rankVal = Math.abs(rankVal);
        request.setAttribute("list", list);
        request.setAttribute("club", club);
        request.setAttribute("type", type);
        request.setAttribute("rankDesc", rankDesc);
        request.setAttribute("rankVal", rankVal);
        return "/template/wap/club/top/top";
    }

    @RequestMapping("/city")
    public String city(HttpServletRequest request, HttpServletResponse response) {
        String ip = WhoisUtil.getIp(request);
        JSONObject obj = intfService.getPlaceByIp(ip);//TODO 迟点改成这个：WhoisUtil.getProvinceAndCity(ip)
        String cityName = "广州";
        long cityId = 0;
        if (cityId == 0 && obj != null) {
            if (cityId == 0 && !obj.get("cityCode").toString().equals("null")) {
                cityId = obj.getIntValue("cityCode");
                cityName = obj.getString("cityName");
            }
        }
        //TODO 再去拿areaCode||页面也要修改
        if (cityId == 0) {
            log.error("通过IP获取不到城市ID[{}]", ip);
            cityId = 440100;//广州市
        }
        request.setAttribute("cityId", cityId);
        request.setAttribute("cityName", cityName.split("市")[0]);
        return "/template/wap/club/city_club";
    }

    /**
     * 获取车友会详细资料
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    public String clubInfo(HttpServletRequest request, HttpServletResponse response) {
        long clubId = WebUtils.paramLong(request, "clubId", 0L);
        Club club = clubService.getValidClub(clubId);
        if (clubId == 0L || club == null) {
            return ERROR_PAGE_REDIRECT_URL;
        }

        request.setAttribute("club", club);
        return "/template/wap/club/info";
    }

    @RequestMapping(value = "/promotion")
    public String cityPromotion(HttpServletRequest request, HttpServletResponse response) {
        return "/template/wap/club/promotion";
    }

    /**
     * 获取同城优惠
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/loadPromotion")
    @ResponseBody
    public void loadCityPromotion(HttpServletRequest request, HttpServletResponse response) throws IOException {
        WebUtils.setEncoding(request, response);
        String callback = WebUtils.param(request, "callback", "");
        JSONObject json = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        long provinceId = WebUtils.paramLong(request, "proCode", 0);
        long cityId = WebUtils.paramLong(request, "cityCode", 0);
        int pageNo = WebUtils.paramInt(request, "pageNo", 1);
        int pageSize = WebUtils.paramInt(request, "pageSize", 10);
        try {
            Pager<Promotion> pager = promotionService.pagetongChen(provinceId, cityId, pageNo, pageSize);
            if (pager != null) {
                List<Promotion> list = pager.getResultList();
                if (list != null && list.size() > 0) {
                    for (Promotion promotion : list) {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("promotionId", promotion.getPromotionId());
                        jsonObject.put("name", promotion.getName());
                        jsonObject.put("url", promotion.getUrl());
                        jsonObject.put("logo", promotion.getLogo());
                        jsonObject.put("introduce", promotion.getIntroduce());
                        jsonObject.put("topicId", promotion.getTopicId());
                        jsonArray.add(jsonObject);
                    }
                }
                json.put("code", AppUtils.STATUS_OK);
                json.put("data", jsonArray);
                json.put("total", pager.getTotal());
                json.put("pageCount", pager.getPageCount());
            }
        } catch (Exception e) {
            json.put("data", jsonArray);
            json.put("total", 0);
            json.put("pageCount", 0);
            log.error("loadCityPromotion exception..", e);
        }
        if (StringUtils.isBlank(callback)) {
            response.getWriter().println(json.toString());
        } else {
            response.getWriter().println(EncodeUtils.encodeForHTML(callback, 2) + "(" + json.toString() + ")");
        }
        response.getWriter().close();
    }

    /**
     * 同城首页
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/tongCheng")
    public String tongCheng(HttpServletRequest request, HttpServletResponse response) {
        User user = userAuth.getUser(request, response);
        Club club = null;
        boolean isMember = false;
        if (user != null) {
            ClubMember clubMember = memberService.findClubMemberByUserId(user.getUid());
            if (clubMember != null) {
                club = clubService.getClub(clubMember.getClubId());
                if (club != null) {
                    isMember = memberService.isClubMember(user.getUid(), club.getClubId());
                }
            }
        }
        request.setAttribute("user", user);
        request.setAttribute("club", club);
        request.setAttribute("myUrl", club == null ? "" : club.getClubUrl());
        request.setAttribute("isMember", isMember);
        return "/template/wap/tongcheng/tongChengList";
    }

    /**
     * App升级页面
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/levelPrizes", method = RequestMethod.GET)
    public String levelPrizes(HttpServletRequest request, HttpServletResponse resp) {
    	long clubId = WebUtils.paramLong(request, "clubId", 0);
        String from = WebUtils.param(request, "from", "app");
        Club club = clubService.getValidClub(clubId);
        if (club == null) {
            log.warn("not found club: {}", clubId);
            return "redirect:" + systemConfig.getWapRoot();
        }
        User user = userAuth.getUser(request, resp);
        request.setAttribute("userSessionName", systemConfig.getUserSessionName());
        request.setAttribute("commonsessionId",passport.recognize(request, resp).getSessionId());
        request.setAttribute("from", from);
        String commonCookie = cn.pconline.passport2.util.WebUtils.getCookie(request, systemConfig.getUserSessionName());
        log.info("{} get passport cookie: {}={}", user.getUid(), systemConfig.getUserSessionName(), commonCookie);
        if (!memberService.isClubOwner(user.getUid(), clubId)) {
            log.warn("not club admin: {}", user.getUid());
            if (!"wap".equals(from)) {
                return "redirect:pcation://goback";
            } else {
                return "redirect:" + systemConfig.getWapRoot() + "/" + club.getClubUrl();
            }
        }
        int isValid = clubLevelService.isUpLevel(club);
        if (isValid != ClubLevelService.CAN_UP_LEVEL) {
            if (!"wap".equals(from)) {
                return "redirect:pcation://goback";
            } else {
                return "redirect:" + systemConfig.getWapRoot() + "/" + club.getClubUrl();
            }
        }
        ClubLevel nextLevel = clubLevelService.getNextLevel(club.getLevelId());
        if (nextLevel != null) { 
            UpgradeRule rule = upgradeRuleService.findUpgradeRuleByLevelId(nextLevel.getLevelId());
            int descNum = 1;
            if(rule != null){
	              	String[] ruleDescArra = rule.getRuleDesc().split("\r\n");
	              	String ruleDesc = "";
	              	for(String str : ruleDescArra){
	              		ruleDesc += "<div class='m-hd-tit'><span>"+descNum+".</span><p>"+str+"</p></div>";
	              		descNum++;
	              	}
	              	rule.setRuleDesc(ruleDesc);
            }
            request.setAttribute("clubLevel", nextLevel);
            request.setAttribute("rule", rule);
            request.setAttribute("descNum", descNum);
            request.setAttribute("levelId", nextLevel.getLevelId());
            request.setAttribute("clubId", clubId);
        } else {
            log.warn("not next level: {}", club.getLevelId());
            if (!"wap".equals(from)) {
                return "redirect:pcation://goback";
            } else {
                return "redirect:" + systemConfig.getWapRoot() + "/" + club.getClubUrl();
            }
        }
        return "template/wap/uplevel/upLevelPrizes";     
    }

    /**
     * app 页面升级方法
     *
     * @param resp
     * @param str
     */
    @RequestMapping(value = "/updateClubLevel")
    public String updateClubLevel(HttpServletRequest request, HttpServletResponse resp) {
        try {
            long clubId = WebUtils.paramLong(request, "clubId", 0);
            long levelId = WebUtils.paramLong(request, "levelId", 0);
            Club club = clubService.getValidClub(clubId);
            if (club == null) {
                this.printMsg(resp, STATUS_FALT, "找不到该车友会", null);
                return null;
            }
            // 是否登录
            User user = userAuth.getUser(request, resp);
            if (user == null || user.getUid() == 0) {
                this.printMsg(resp, STATUS_FALT, "您是游客，请登录后再操作", null);
                return null;
            }
            // 是否会长
            ClubMember clubMember = memberService.findMember(user.getUid(), clubId);
            if (clubMember == null) {
                this.printMsg(resp, STATUS_FALT, "您不是该车友会成员，无法操作!", null);
                return null;
            }
            if (!clubMember.isAdmin()) {
                this.printMsg(resp, STATUS_FALT, "您不是会长，无法操作!", null);
                return null;
            }
            if (club.getStatus() == Club.STATUS_LOCK) {
                this.printMsg(resp, STATUS_FALT, "车友会已经被锁定，无法操作!", null);
                return null;
            }

            if (club.getStatus() == Club.STATUS_REJECTED) {
                this.printMsg(resp, STATUS_FALT, "车友会已经被封，无法操作!", null);
                return null;
            }

            String name = WebUtils.paramTrim(request, "name", "");
            String phone = WebUtils.paramTrim(request, "phone", "");
            String address = WebUtils.paramTrim(request, "address", "");
            String postalCode = WebUtils.paramTrim(request, "postalCode", "");
            if (StringUtils.isEmpty(name) || name.length() > 20) {
                this.printMsg(resp, STATUS_FALT, "名字不能为空或名字过长", null);
                return null;
            }
            if (StringUtils.isEmpty(phone) || phone.length() > 20) {
                this.printMsg(resp, STATUS_FALT, "联系方式不能为空或过长", null);
                return null;
            }
            if (StringUtils.isEmpty(address) || address.length() > 100) {
                this.printMsg(resp, STATUS_FALT, "地址不能为空或地址过长", null);
                return null;
            }
            if (StringUtils.isEmpty(postalCode) || postalCode.length() > 6) {
                this.printMsg(resp, STATUS_FALT, "邮编不能为空或邮编过长", null);
                return null;
            }
            ClubAwardRecord awardRecord = recordService.findByClubId(clubId, levelId);
            if (awardRecord == null) {
                int isUp = clubLevelService.isUpLevel(club);
                if (isUp < 4 && isUp > 0) {
                    this.printMsg(resp, STATUS_FALT, "未达到领取福利标准，无法修改收货人信息", null);
                    return null;
                } else if (isUp == 5) {
                    ClubAwardRecord awRecord = new ClubAwardRecord();
                    awRecord.setClubId(clubId);
                    awRecord.setLevelId(levelId);
                    awRecord.setUpdateTime(DateUtils.getNow());
                    awRecord.setName(name);
                    awRecord.setPhone(phone);
                    awRecord.setAddress(address);
                    awRecord.setPostalCode(postalCode);
                    recordService.create(awRecord);
                    //this.printMsg(resp,STATUS_SUCCESS, "修改成功",null);
                }
            } else if (awardRecord.getReceived() == ClubAwardRecord.RECEIVED_YES) {
                //this.printMsg(resp, STATUS_FALT, "该级别福利已经领取，无法修改收货人信息！", null);
                //return null;
            } else if (awardRecord.getReceived() == ClubAwardRecord.RECEIVED_NO) {
                awardRecord.setName(name);
                awardRecord.setPhone(phone);
                awardRecord.setAddress(address);
                awardRecord.setPostalCode(postalCode);
                recordService.update(awardRecord);
                //this.printMsg(resp,STATUS_SUCCESS, "修改成功",null);
            }
            //升级操作
            Map<Boolean, String> info = clubService.updateClubLevel(clubId, levelId);

            if (info.containsKey(true)) {
                ClubAwardRecord c = recordService.findByClubId(clubId, levelId);
                if (c.getReceived() == ClubAwardRecord.RECEIVED_NO) {
                    c.setReceived(ClubAwardRecord.RECEIVED_YES);
                    c.setAcceptDate(DateUtils.getNow());//更新领奖时间
                    recordService.update(c);
                    this.printMsg(resp, STATUS_SUCCESS, "领取成功，太平洋汽车网会尽快将福利快递给您，请您注意查收！", null);
                    //给所有车友会成功发送升级信息,只有在第一次升级的时候才会发信息
                    //clubLevelService.setMsgToMember(clubId);
                    return null;
                } else if (c.getReceived() == ClubAwardRecord.RECEIVED_YES) {
                    this.printMsg(resp, STATUS_FALT, "该级别福利已领取", null);
                    return null;
                } else {
                    this.printMsg(resp, STATUS_FALT, "车友会升级失败", null);
                    return null;
                }
            } else {
                this.printMsg(resp, STATUS_FALT, info.get(false), null);
            }


        } catch (Exception ex) {
            this.printMsg(resp, STATUS_FALT, "修改出错了", null);
        }
        return null;
    }
    
    /**
     * WAP创建车友会，第一步填写车友会资料
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/createClubStep1Page.do")
    public String createClubStep1Page(HttpServletRequest request, HttpServletResponse response) {
        User user = checkAndSetUser(request, response);
        ClubDraft clubDraft = null;
        if(user != null && user.getUid() > 0) {
        	clubDraft = clubDraftService.findDraftByUserId(user.getUid());
        	if(clubDraft == null) {
        		clubDraft = new ClubDraft();
        		clubDraft.setCreateBy(user.getUid());
        		clubDraft.setUserId(user.getUid());
        		clubDraft.setCreateAt(new Date());
        		clubDraftService.createOrUpdate(clubDraft);
        	}
        }
    	
        List<Theme> themes = themeService.listAllThemes();
        request.setAttribute("themes", themes);
        request.setAttribute("TYPE_AREA", Club.TYPE_AREA);
        request.setAttribute("TYPE_SERIAL", Club.TYPE_SERIAL);
        request.setAttribute("TYPE_THEME", Club.TYPE_THEME);
        request.setAttribute("clubDraft", clubDraft);
        
        //用户与车友会关系描述
        String tips = "";
        if(user != null) {
        	tips = clubService.checkJoinedClub(user);
        }
        request.setAttribute("joinedClubTips", tips);
        
        return "/template/wap/club/createClubStep1";
    }
    
    /**
     * 创建车友会第一步(创建草稿)
     * @param request
     * @param resp 
     */
    @RequestMapping(value="/createClubStep1Action.do",method= RequestMethod.POST)
    public void createClubStep1Action(HttpServletRequest request, HttpServletResponse resp) {
        WebUtils.setEncoding(request, resp);
        //当该方法返回null的时候证明没登录,提示信息已经在checkAndSetUser返回, 只有在POST接口有效
        User user = checkAndSetUser(request, resp);
        if(user == null) {
        	return;
        }
        //检查车友会信息并组装车友会草稿
        ClubDraft clubDraft = assemblingAndCheckClubInfo(request, resp,user);
        if (clubDraft==null) {
            return;
        }
       int count =  clubDraftService.createOrUpdate(clubDraft);
       if (count>0){
           printMsg(resp, STATUS_SUCCESS, "申请成功", "");
       }else{
    	   printMsg(resp, STATUS_FALT, "申请失败", "");
       }
    }
    
    /**
     * 创建第二步页面跳转
     * @param request
     * @param resp
     * @return 
     */
    @RequestMapping(value="/createClubStep2Page.do",method= RequestMethod.GET)
    public String createClubStep2Page(HttpServletRequest request, HttpServletResponse resp){
        //当该方法返回null的时候证明没登录,提示信息已经在checkAndSetUser返回, 只有在POST接口有效
        User user = checkAndSetUser(request, resp);
        if (user == null) {
            return null;
        }
        ClubDraft clubDraft = clubDraftService.findDraftByUserId(user.getUid());
        if(clubDraft == null ){
             request.setAttribute("msg", "请一步一步填写,先填写车友会信息!");
            return "/template/club/foundFail";
        }
        
        //用户与车友会关系描述
        String tips = "";
        if(user != null) {
        	tips = clubService.checkJoinedClub(user);
        }
        request.setAttribute("joinedClubTips", tips);
        
        return "/template/wap/club/createClubStep2";
    }
    /**
     * 创建车友会第二步(保存车友会地址和生成车友会记录)
     * @param request
     * @param resp 
     */
    @RequestMapping(value="/createClubStep2Action.do",method= RequestMethod.POST)
    public void createClubStep2Action(HttpServletRequest request, HttpServletResponse resp){
        WebUtils.setEncoding(request, resp);
        //当该方法返回null的时候证明没登录,提示信息已经在checkAndSetUser返回, 只有在POST接口有效
        User user = checkAndSetUser(request, resp);
        if ( user == null ) {
            return;
        }
     
        String realName = WebUtils.param(request, "name", "");
        String checkRealNamResult = clubService.checkRealName(realName);
        if(!checkRealNamResult.equals("true")){
            printMsg(resp, STATUS_FALT, checkRealNamResult, "name");
            return;
        }
        
        String phone = WebUtils.param(request, "phone", "");
        if(StringUtils.isBlank(phone)){
        	printMsg(resp, STATUS_FALT, "手机号码不能为空", "phone");
            return;
        }
        String code = WebUtils.paramTrim(request, "code", "");
        if (StringUtils.isBlank(code)) {
        	printMsg(resp, STATUS_FALT, "请输入验证码", "code");
            return;
        }
        int gender = WebUtils.paramInt(request, "gender", 0);
        String postCode = WebUtils.param(request, "postCode", "");
        String address = WebUtils.param(request, "address", "");
        if (systemConfig.isNeedCheckCode()) {
            String checkCodeMsg = checkPhoneCode(phone, code);
            if (StringUtils.isNotEmpty(checkCodeMsg)) {
            	printMsg(resp, STATUS_FALT, checkCodeMsg, "code");
                return;
            }
        }
        
        //判断是否已经申请车友会，或已经加入过车友会
        
        String message = this.checkJoinedClub(user);
        if(!StringUtils.isBlank(message)) {
        	printMsg(resp, STATUS_FALT, message, "");
        	return;
        }
        ClubDraft clubDraft = clubDraftService.findDraftByUserId(user.getUid());
        if(clubDraft!=null){
            Club club = clubDraftService.parseClubDraftToClub(clubDraft);
            if(club!=null){
            	ClubAddress clubAddress = new ClubAddress();
                clubAddress.setName(realName);
                clubAddress.setPhone(phone);
                clubAddress.setUpdateAt(new Date());
                clubAddress.setAddress(address);
                clubAddress.setPostcode(postCode);
                clubAddress.setClubId(club.getClubId());
                clubAddress.setProvinceId(club.getProvinceId());
                clubAddress.setProvinceName(club.getProvinceName());
                clubAddress.setCityId(club.getCityId());
                clubAddress.setCityName(club.getCityName());
                //创建车友会，车友会地址表，油值
                long clubId =  clubService.create(club, clubAddress);
                //保存个人资料到ac_user
                user.setTruename(realName);
                user.setGender(gender);
                user.setPhone(phone);
                userService.updateUser(user);
                //保存到个人中心
                sendToMyCenter(request, realName, gender, phone);
               
                if( clubId > 0 ){
            	    printMsg(resp, STATUS_SUCCESS, "创建成功", "");
                }else{
            	    printMsg(resp, STATUS_FALT, "创建失败", "");
                }
            }
        }else{
        	printMsg(resp, STATUS_FALT, "请先填写第一步操作", "");
        }
    }
    
    /**
     * 校验车友会信息
     * @param club
     * @param resp
     * @return 
     */
    private boolean checkClubInfo(Club club,HttpServletResponse resp){
        String retNameMsg = clubService.checkClubName(club.getName());
        if (!"true".equals(retNameMsg)) {
            printMsg(resp, STATUS_FALT, retNameMsg, "name");
            return false;
        }
        String retUrlMsg = clubService.checkClubUrl(club.getClubUrl());
        if (!"true".equals(retUrlMsg)) {
        	printMsg(resp, STATUS_FALT, retUrlMsg, "clubUrl");
            return false;
        }
        if (club.getProvinceId() != 0 && StringUtils.isBlank(club.getProvinceName())) {
        	printMsg(resp, STATUS_FALT, "缺少省份名称", "areaParentTag_cityId");
            return false;
        } else if (!club.getProvinceName().isEmpty()) {
        	if(club.getProvinceName().length() > INPUT_MAX_LENGTH){
        	  printMsg(resp, STATUS_FALT, "非法省份名称", "areaParentTag_cityId");
              return false;
        	}
        }
        if (club.getCityId() != 0 && StringUtils.isBlank(club.getCityName())) {
        	printMsg(resp, STATUS_FALT, "缺少城市名称", "cityId");
            return false;
        } else if (club.getCityName().length() > INPUT_MAX_LENGTH) {
        	printMsg(resp, STATUS_FALT, "非法城市名称", "cityId");
            return false;
        }
        if (club.getBrandId() != 0 && StringUtils.isBlank(club.getBrandName())) {
        	printMsg(resp, STATUS_FALT, "缺少品牌名称", "brandId");
            return false;
        }
        if (!StringUtils.isBlank(club.getBrandName()) && !club.getBrandName().isEmpty()) {
        	if(club.getBrandName().length() > INPUT_MAX_LENGTH){
        	  printMsg(resp, STATUS_FALT, "非法品牌名称", "brandId");
              return false;
        	}
        }
        
        if (club.getSeriesId() != 0 && StringUtils.isBlank(club.getSeriesName())) {
        	printMsg(resp, STATUS_FALT, "缺少车系名称", "seriesId");
            return false;
        } else if (!club.getSeriesName().isEmpty()) {
        	if(club.getSeriesName().length() > INPUT_MAX_LENGTH){
        	  printMsg(resp, STATUS_FALT, "非法车系名称", "seriesId");
              return false;
        	}
        }
        if (club.getProvinceId() == 0 && club.getCityId() != 0) {//非法操作
        	printMsg(resp, STATUS_FALT, "缺少省份", "cityId");
            return false;
        }
        if (club.getBrandId() == 0 && club.getSeriesId() != 0) {//非法操作
        	printMsg(resp, STATUS_FALT, "缺少品牌", "seriesId");
            return false;
        }
        if (club.getType() == Club.TYPE_AREA) {//省份或地区
            if (club.getProvinceId() == 0) {
            	printMsg(resp, STATUS_FALT, "请选择省份", "areaParentTag_cityId");
                return false;
            }
            if (club.getCityId() == 0) {
            	printMsg(resp, STATUS_FALT, "请选择城市", "cityId");
                return false;
            }
        } else if (club.getType() == Club.TYPE_SERIAL) {//允许只选品牌车系
            if (club.getBrandId() == 0) {
            	printMsg(resp, STATUS_FALT, "请选择品牌", "brandId");
                return false;
            }
            if (club.getSeriesId()== 0) {
            	printMsg(resp, STATUS_FALT, "请选择车系", "seriesId");
                return false;
            }
        } else if (club.getType() == Club.TYPE_THEME) {
            if (club.getThemeId() == 0) {
            	printMsg(resp, STATUS_FALT, "请选择主题", "themeId");
                return false;
            }
        } else {
        	printMsg(resp, STATUS_FALT, "请选择车友会类型", "clubType");
            return false;
        }
        String qqGroupMsg = clubService.checkClubQQGroup(club.getQqGroup());
        if (!"true".equals(qqGroupMsg)) {
        	printMsg(resp, STATUS_FALT, qqGroupMsg, "qqGroup");
            return false;
        }
        return true;
    }
    
    /**
     * 组装车友会信息
     * @param request
     * @param user
     * @return 
     */
    private Club assemblingClub(HttpServletRequest request,User user){
        String name = WebUtils.paramTrim(request, "name", "");
        String clubUrl = WebUtils.paramTrim(request, "clubUrl", "").replaceAll(" ", "").toLowerCase();
        long themeId = WebUtils.paramLong(request, "themeId", 0);
        int clubType = WebUtils.paramInt(request, "clubType", -1);
        long provinceId = WebUtils.paramLong(request, "provinceId", 0);
        String provinceName = WebUtils.paramTrim(request, "provinceName", "");
        long cityId = WebUtils.paramLong(request, "cityId", 0);
        String cityName = WebUtils.getAreaPlaceByReq(request, "cityName", "");
        long brandId = WebUtils.paramLong(request, "brandId", 0);
        String brandName = WebUtils.getAreaPlaceByReq(request, "brandName", "");
        long seriesId = WebUtils.paramLong(request, "seriesId", 0);
        String seriesName = WebUtils.paramTrim(request, "seriesName", "");
        String qqGroup = WebUtils.paramTrim(request, "qqGroup", "");
        long regionId = RegionUtil.getRegionId(provinceId);
        String regionName = RegionUtil.getRegionName(regionId);
        Date currentDate = new Date();
        Club club = new Club();
        club.setType(clubType);
        club.setAdminId(user.getUid());
        club.setAuditAt(null);
        club.setAuditBy(0);
        club.setThemeId(themeId);
        club.setBrandId(brandId);
        club.setCityId(cityId);
        club.setCityName(cityName);
        club.setCreateAt(currentDate);
        club.setCreateBy(user.getUid());
        club.setIntroduce("");
        club.setLevelId(0);
        club.setLogo("");
        club.setMemberNum(0);
        club.setName(name);
        club.setProvinceId(provinceId);
        club.setProvinceName(provinceName);
        club.setRegionId(regionId);
        club.setRegionName(regionName);
        club.setReplyNum(0);
        club.setSeriesId(seriesId);
        club.setSeriesName(seriesName);
        club.setStatus(Club.STATUS_UNAUDITED);
        club.setTopicNum(0);
        club.setUpdateAt(currentDate);
        club.setUpdateBy(user.getUid());
        club.setVipNum(0);
        club.setClubUrl(clubUrl);
        club.setQqGroup(qqGroup);
        if (StringUtils.isNotBlank(brandName)) {
            club.setBrandName(brandName.substring(2, brandName.length()));
        }
         if (club.getType() == Club.TYPE_AREA) {//
            //选了地区，其他不必填
             club.setThemeId(0);
             club.setBrandId(0);
             club.setBrandName("");
             club.setSeriesId(0);
             club.setSeriesName("");
        } else if (club.getType() == Club.TYPE_SERIAL) {
            //选了品牌/车系，主题不必填
          club.setThemeId(0);
        }
         return club;
    }
    
    /**
     * 组装车友会草稿并检查车友会信息
     * @param request
     * @param resp
     * @param user
     * @return 
     */
    private ClubDraft assemblingAndCheckClubInfo(HttpServletRequest request, HttpServletResponse resp,User user) {
        Club club = assemblingClub(request,user);
        if(!checkClubInfo(club, resp)){
            return null;
        }
        //创建车友会草稿
        ClubDraft clubDraft = clubDraftService.parseClubToClubDraft(club);
        return clubDraft;
    }
    
    /**
     * 判断是否登录
     *
     * @param request
     * @param resp
     */
    private User checkAndSetUser(HttpServletRequest request, HttpServletResponse resp) {
        User user = userAuth.getUser(request, resp);
        if (user.getUid() <= 0) {
            if (WebUtils.isGet(request)) {
                try {
                    String uri = request.getRequestURI();
                    if(uri.indexOf("/wap/") == 0) {
                        uri = uri.replace("/wap/", "/");
                    }
                    String url = systemConfig.getUcRoot()
                            + "/login.jsp?return="
                            + systemConfig.getWapRoot() + uri;
                    if (request.getQueryString() != null) {
                        url += "?" + request.getQueryString();
                    }
                    resp.sendRedirect(url);
                } catch (IOException ex) {
                    log.error("checkAndSetUser error");
                }
            } else {
            	printMsg(resp, STATUS_FALT, "没有登录", "");
                return null;
            }
        }
        request.setAttribute("user", user);
        return user;
    }
    
    /**
     * 返回验证结果，如果为空串就表示验证通过，否则返回验证信息
     *
     * @param phone
     * @param code
     * @return
     */
    @SuppressWarnings("unused")
    private String checkPhoneCode(String phone, String code) {
        String relUrl = systemConfig.getRoot() + "/ClubController.found.checkPhoneCode";
        String url = systemConfig.getCheckCodeUrl();
        String result = simpleHttpTemplate.post(url, relUrl, null,
                new ResponseExtractor<String>() {
                    @Override
                    public String extractData(HttpResponse response) {
                        StatusLine statusLine = response.getStatusLine();
                        if (statusLine.getStatusCode() == 200) {
                            try {
                                return EntityUtils.toString(response.getEntity());
                            } catch (IOException ex) {
                                log.error("checPhoneCode fail 1!", ex);
                            } catch (ParseException ex) {
                                log.error("checPhoneCode fail 2!", ex);
                            }
                        } else {
                            log.error("checPhoneCode fail statusCode is " + statusLine.getStatusCode());
                            try {
                                log.error(EntityUtils.toString(response.getEntity()));
                            } catch (IOException ex) {
                                log.error("checkAndSetUser error", ex);
                            } catch (ParseException ex) {
                                log.error("checkAndSetUser error", ex);
                            }
                        }
                        return null;
                    }
                },
                EntityBuilder.entity().param("type", "autoClub").param("act", "check").param("mobile", phone).param("verificationCode", code).build(), 3000);
        JSONObject rs = JSONObject.parseObject(result);
        if (rs == null) {
            return "手机验证出错，请稍后重试";
        }
        int c = rs.getIntValue("code");
        if (c == 0) {
            return "";
        }
        return rs.getString("message");
    }
    
    /**
     * 判断用户是否已经加入过车会，如果已经加入过，或者申请中的用户不可以创建车友会
     *
     * @param user
     * @return
     */
    @SuppressWarnings("unused")
    private String checkJoinedClub(User user) {
        int limit = Integer.parseInt(systemConfig.getJoinClubLimit());
        String tip = "";
        int count = userService.updateJoinedClubCount(user);
        if (count >= limit) {
            tip = "您已加入其他车友会，无法创建！";
            return tip;
        }
        count += memberService.findMemberApplication(user.getUid(), 0l, true).size();
        if (count >= limit) {
            tip = "您已申请加入其他车友会，如要创建新车友会，请取消之前的申请！";
            return tip;
        }
        count += clubService.findByFounder(user.getUid(), false).size();
        if (count >= limit) {
            tip = "您已申请创建另一个车友会，如要创建新车友会，请取消之前的申请！";
            return tip;
        }
        return tip;
    }
    
    /**
     * 创建车友会成功页面
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/createClubSuccessPage.do", method = RequestMethod.GET)
    public String createClubSuccessPage(HttpServletRequest request, HttpServletResponse response) {
    	WebUtils.setEncoding(request, response);
    	return "/template/wap/club/createClubSuccess";
    }
    
    /**
     * 创建车友会成功问题咨询页面
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/createClubQuestionPage.do", method = RequestMethod.GET)
    public String createClubQuestionPage(HttpServletRequest request, HttpServletResponse response) {
    	WebUtils.setEncoding(request, response);
    	return "/template/wap/club/createClubQuestion";
    }
    
    /**
     * 实时获取短信验证码防刷KEY
     *
     * @param req
     * @param resp
     */
    @RequestMapping(value = "/getVCodeKey.do", method = RequestMethod.GET)
    public void getVCodeKey(HttpServletRequest req, HttpServletResponse resp) {
        WebUtils.setEncoding(req, resp);
        String callback = WebUtils.param(req, "callback", "");
        String Vkey = "sendVerificationCode.jsp";
        long vCodeTime = System.currentTimeMillis();
        String vCodeKey = WebUtils.md5(Vkey + vCodeTime);
        JSONObject obj = new JSONObject();
        obj.put("code", 0);
        obj.put("vCodeTime", vCodeTime);
        obj.put("vCodeKey", vCodeKey);
        print(resp, obj.toJSONString(), callback);
    }
  
    
    /**
     * 同步个人资料到个人中心
     * @param params
     * @return
     */
    private String sendToMyCenter(HttpServletRequest request, String realName, int gender, String phone ) {
        String commonSessionId = cn.pconline.passport2.util.WebUtils.getCookie(request, systemConfig.getUserSessionName());
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("realName", realName);
        params.put("gender", gender==0?MALE:FEMALE);
        params.put("telephone", phone);
        params.put("act", ACT_SAVE);
        params.put(systemConfig.getUserSessionName(), commonSessionId);
        String ucRoot = systemConfig.getUcRoot();
        String result = simpleHttpTemplate.post(ucRoot + "/intf/club/updateUser.jsp", null, new ResponseExtractor<String>() {
            @Override
            public String extractData(HttpResponse response) throws IOException {
                StatusLine statusLine = response.getStatusLine();
                if (statusLine.getStatusCode() == 200) {
                    try {
                        return EntityUtils.toString(response.getEntity());
                    } catch (IOException ex) {
                        log.error("sendToMyCenter fail 1!", ex);
                    } catch (ParseException ex) {
                        log.error("sendToMyCenter fail 2!", ex);
                    }
                } else {
                    log.error("sendToMyCenter fail statusCode is " + statusLine.getStatusCode());
                    try {
                        log.error(EntityUtils.toString(response.getEntity()));
                    } catch (IOException ex) {
                        log.error("sendToMyCenter fail--IOException", ex);
                    } catch (ParseException ex) {
                        log.error("sendToMyCenter fail--ParseException", ex);
                    }
                }
                return "";
            }
        }, EntityBuilder.entity().params(params).build());
       
        return result;
    }
    
    /**
     * 会员卡页面跳转
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/getMemberShipCard.do", method = RequestMethod.GET)
    public String getMemberShipCard(HttpServletRequest request, HttpServletResponse response){
    	// 判断用户是否登录
        User user = userAuth.getUser(request, response);
        if (user == null || user.getUid() == 0L) {
            return "redirect:" + systemConfig.getUcWapRoot() + "/passport/login.jsp?return=" + systemConfig.getWapRoot() + "/club/getMemberShipCard.do";
        }
        
        long userId = user.getUid();
        request.setAttribute("NO", userId);
        return "template/wap/club/memberShipCard";
    }
    
    /**
     * 打开一键邀请
     *
     * @param request
     * @param model
     * @param resp
     * @return
     */
    @RequestMapping(value = "/getInviteLink.do", method = RequestMethod.GET)
    public String getInviteLink(HttpServletRequest request, Model model, HttpServletResponse resp) {
        String inviteCode = WebUtils.paramTrim(request, "code", "");
        if (StringUtils.isBlank(inviteCode)) {
            try {
                resp.sendError(404);
                return null;
            } catch (IOException ex) {
                log.error("error", ex);
            }
        }
        InviteJoin inviteJoin = inviteJoinService.getAllInviteJoinByCode(inviteCode);
        Club club = null;
        if (inviteJoin == null) {
            request.setAttribute("msg", "该邀请链接不存在");
            return "/template/wap/club/common/errorPop";
        } else if(inviteJoin.isOverdue()) {
            request.setAttribute("msg", "该邀请链接已过期");
            request.setAttribute("isFail", true);
            club = clubService.getValidClub(inviteJoin.getClubId());
            if (club != null) {
                User user = userService.findUser(club.getAdminId());
                request.setAttribute("user", user);
            }
            request.setAttribute("club", club);
            return "/template/wap/club/common/errorPop";
        }
        long adminId = inviteJoin.getCreateBy();
        User user = userService.findUser(adminId);
        club = clubService.getValidClub(inviteJoin.getClubId());
        ClubMember inviteUser = memberService.findMember(inviteJoin.getCreateBy(), club.getClubId());
        if (club == null || user == null || inviteUser == null) {
            request.setAttribute("msg", "该邀请链接已失效");
            return "/template/wap/club/common/errorPop";
        }
        int count = memberService.countMembersByClubId(club.getClubId());
        List<ClubMember> lastestMembers = memberService.getLastestMember(club.getClubId(), DISPLAY_LASTEST_COUNT);
        userService.loadTransientUsers(lastestMembers);
        request.setAttribute("members", lastestMembers);
        request.setAttribute("count", count);
        request.setAttribute("user", user);
        request.setAttribute("club", club);
        request.setAttribute("inviteJoin", inviteJoin);
        return "/template/wap/club/invite";
    }
    
    /**
     * 一键邀请(个人信息)
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/inviteJoin.do")
    public String inviteJoin(HttpServletRequest req, HttpServletResponse resp) {
        String code = WebUtils.param(req, "code", "");
        if (StringUtils.isBlank(code)) {
            try {
                resp.sendError(404);
                return null;
            } catch (IOException ex) {
                log.error("error", ex);
            }
            return null;
        }

        InviteJoin inviteJoin = inviteJoinService.getAllInviteJoinByCode(code);
        Club club = null;
        if (inviteJoin == null) {
             req.setAttribute("msg", "该邀请链接不存在");
             return "template/wap/club/common/errorPop";
        }else if(inviteJoin.isOverdue()){ //是否过期
             req.setAttribute("msg", "该邀请链接已过期");
             req.setAttribute("isFail", true);
             club = clubService.getValidClub(inviteJoin.getClubId());
             if (club != null) {
                    User adminUser = userService.findUser(club.getAdminId());
                    req.setAttribute("user", adminUser);
              }
              req.setAttribute("club", club);
              return "template/wap/club/common/errorPop";
            }
        club = clubService.getValidClub(inviteJoin.getClubId());
        req.setAttribute("club", club);
        if(club == null){
             req.setAttribute("msg", "该车友会不存在");
            return "template/wap/club/common/errorPop";
        }
        
        ClubMember inviteUser = memberService.findMember(inviteJoin.getCreateBy(), club.getClubId());
        if(inviteUser == null) {
             req.setAttribute("msg", "该邀请链接已失效");
             return "template/wap/club/common/errorPop";
        }
        req.setAttribute("isAdmin", inviteUser.isAdministrator());
        
        User user = userAuth.getUser(req, resp);
        if (user == null || user.getUid() == 0) {
            req.setAttribute("PASSPORT", systemConfig.getPassportRoot());
            req.setAttribute("returnUrl", systemConfig.getWapRoot() + "/invite/info/" + code + "/"+"invite.html");
            req.setAttribute("code", code);
            return "template/wap/club/inviteLogin";
        }
        
        if (memberService.isClubMember(user.getUid(), club.getClubId())) {
            req.setAttribute("msg", "已经加入该车友会");
            return "template/wap/club/common/errorPop";
        }
        //验证加入车友会个数
        int count = userService.updateJoinedClubCount(user);
        if (count>= NumberUtils.toInt(systemConfig.getJoinClubLimit(), 1)) {
            req.setAttribute("msg", "已经加入其他车友会,无法再加入该车友会");
            req.setAttribute("isJoin", true);
            ClubMember clubMember = memberService.findClubMemberByUserId(user.getUid());
            if (clubMember != null) {
                req.setAttribute("club", clubService.getValidClub(clubMember.getClubId()));
            }
            return "template/wap/club/common/errorPop";
        }
        if (!memberService.findMemberApplication(user.getUid(), club.getClubId(), true).isEmpty()) {
            req.setAttribute("msg", "您已经提交申请加入，请等待会长审核");
            return "template/wap/club/common/errorPop";
        }
        if (!memberService.listClubMemberByUser(user.getUid()).isEmpty() || !clubService.findByFounder(user.getUid(), true).isEmpty()) { //已经申请加入另一个车友会 或 已创建一个车友会待审核
            req.setAttribute("msg", "您只能申请或加入一个车友会");
            return "template/wap/club/common/errorPop";
        }
        
        req.setAttribute("user", user);
        req.setAttribute("clubId", club.getClubId());
        req.setAttribute("code", inviteJoin.getInviteCode());
        return "template/wap/club/inviteUserInfo";
    }    
    
    /**
     * 邀请成功
     *
     * @param request
     * @param model
     * @param resp
     * @return
     */
    @RequestMapping(value = "/goInviteSuccess.do", method = RequestMethod.GET)
    public String goInviteSuccess(HttpServletRequest req, HttpServletResponse resp) {
            User user = userAuth.getUser(req, resp);
            long clubId = WebUtils.paramLong(req, "clubId", 0);
            if (user == null || user.getUid() == 0) {
                return "template/wap/club/inviteLogin";
            }
            Club club = null;
            //clubId不为0时测为跳转到申请成功页否则跳转到加入成功页
            if(clubId != 0) {
                club = clubService.getValidClub(clubId);
                req.setAttribute("isInviteApply", true);
            } else {
                ClubMember clubMember = memberService.findClubMemberByUserId(user.getUid());
                if(clubMember !=null){
                    club = clubService.getClub(clubMember.getClubId());
                }
            }
            
            req.setAttribute("club", club);
            return "template/wap/club/inviteSuccess";
    }
    /**
     * 返回相关Json信息
     *
     * @param resp
     * @param str
     * @param callback
     */
    private void printMsg(HttpServletResponse resp, int statusCode, String msg, String field) {
        try {
            resp.setCharacterEncoding("UTF-8");
            resp.getWriter().println(
                    new JSONBuilder()
                    .put("statusCode", statusCode)
                    .put("field", field)
                    .put("message", msg)
                    .toString());
        } catch (IOException ex) {
            log.error("response write out error.", ex);
        }
    }
     
    private void print(HttpServletResponse resp, String str, String callback) {
        try {
            java.io.PrintWriter w = resp.getWriter();
            if (StringUtils.isNotBlank(callback)) {
                w.println(EncodeUtils.encodeForHTML(callback, DEF_SOURCE_AGENT) + "(" + str + ")");
            } else {
                w.println(str);
            }
            w.flush();
            w.close();
        } catch (IOException ex) {
            log.error("error", ex);
        }
    }
    /**
     *
     * 获取车友会列表接口(APP)
     *
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "/getClubByCityOrRegionId.do", method = RequestMethod.GET)
    public void getClubByCityOrRegionId(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        WebUtils.setEncoding(req, resp);
        String callback = WebUtils.param(req, "callback", "");
        long cityId = WebUtils.paramInt(req, "cityId", 0);
        long provinceId = WebUtils.paramInt(req, "provinceId", 0);
        long seriesId = WebUtils.paramInt(req, "seriesId", 0);
        String clubName = WebUtils.paramTrim(req, "clubName", "");
        long clubId = WebUtils.paramLong(req, "clubId", 0);
        long brandId = WebUtils.paramInt(req, "brand", 0);
        int pageNo = WebUtils.paramInt(req, "pageNo", 1);
        int pageSize = WebUtils.paramInt(req, "pageSize", 20, MIN_PAGESIZE, MAX_PAGESIZE);
        boolean isXSS = true;
        Pager<Club> pager = clubService.pageClubByPlaceId(cityId, 0, provinceId, brandId, null, clubId, clubName, pageNo, pageSize, 0);
        JSONObject json = new JSONObject();
        if (pager.getResultList() != null && !pager.getResultList().isEmpty()) {
            JSONArray jsonArray = new JSONArray();
            for (Club club : pager.getResultList()) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("clubId", club.getClubId());
                jsonObject.put("name", EncodeUtils.encodeForHTML(club.getName(), isXSS));
                jsonObject.put("logo", EncodeUtils.encodeForHTML(club.getLogo(), isXSS));
                jsonObject.put("memberSum", club.getMemberNum());
                jsonObject.put("totalPetrol", club.getTotalPetrol());
                jsonObject.put("level", club.getLevelId());
                jsonObject.put("clubStatus", club.getStatus());
                jsonObject.put("brandId", club.getBrandId());
                jsonObject.put("seriesName", EncodeUtils.encodeForHTML(club.getSeriesName(), isXSS));
                jsonObject.put("brandName", EncodeUtils.encodeForHTML(club.getBrandName(), isXSS));
                jsonObject.put("provinceName", EncodeUtils.encodeForHTML(club.getProvinceName(), isXSS));
                jsonObject.put("cityName", EncodeUtils.encodeForHTML(club.getCityName(), isXSS));
                jsonObject.put("clubUrl", club.getClubUrl());
                jsonArray.add(jsonObject);
            }
            AppUtils.setSuccessCode(json);
            json.put("data", jsonArray);
            json.put("total", pager.getTotal());
            json.put("pageNo", pager.getPageNo());
            json.put("pageCount", pager.getPageCount());
            json.put("pageSize", pager.getPageSize());
        } else {
            json.put("data", new JSONArray());
            AppUtils.setSuccessCode(json);
        }
        ActionKit.printSuccessMsg(resp, json, callback);
    }
}